package com.cskaoyan.config.zhangshizhi;

import com.cskaoyan.bean.MarketAdmin;
import com.cskaoyan.bean.MarketAdminExample;
import com.cskaoyan.bean.MarketLog;
import com.cskaoyan.bean.MarketLogExample;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.mapper.MarketLogMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author little ants
 * @since 2022/07/01 10:18
 */

@Aspect
@Component
public class CustomAspectJ {

    @Autowired
    MarketLogMapper logMapper;
    @Autowired
    MarketAdminMapper adminMapper;

    private Integer logId;
    private String logIp;
    public static final Integer SUCCESSFUL  = 1;

    private String getIp() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        return request.getRemoteAddr();

    }

    // 登录切入点，controller层
    @Pointcut("execution(* com.cskaoyan.controller.AuthController.login(..))")
    public void loginPointcut() {

    }

    // 通知
    @Before("loginPointcut()")
    private String before() throws Throwable {
        // 获取访问ip
        logIp = getIp();

        MarketLog marketLog = new MarketLog();
        marketLog.setIp(logIp);
        // 默认操作结果为false
        marketLog.setStatus(false);

        // 默认操作类型为1
        marketLog.setType(SUCCESSFUL);

        // 获取操作时间
        Date date = new Date();
        marketLog.setAddTime(date);
        marketLog.setUpdateTime(date);

        marketLog.setAction("登录");

        logMapper.insertSelective(marketLog);

        return null;
    }


    // 通知
    @After("loginPointcut()")
    private String after() {

        MarketLogExample logExample = new MarketLogExample();
        MarketLogExample.Criteria logCriteria = logExample.createCriteria();
        logCriteria.andIpEqualTo(logIp);
        logCriteria.andActionEqualTo("登录");
        List<MarketLog> marketLogs = logMapper.selectByExample(logExample);
        logId = marketLogs.get(marketLogs.size() - 1).getId();


        MarketLog marketLog = new MarketLog();
        // 更改操作结果为true
        marketLog.setStatus(true);

        Subject subject = SecurityUtils.getSubject();
        MarketAdmin principal = (MarketAdmin) subject.getPrincipal();
        String username = principal.getUsername();
        marketLog.setAdmin(username);

        MarketLogExample example = new MarketLogExample();
        MarketLogExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(logId);


        logMapper.updateByExampleSelective(marketLog, example);
        logId = null;
        logIp = null;

        return null;
    }




    // 退出登录切入点
    @Pointcut("execution(* com.cskaoyan.controller.AuthController.logout(..))")
    public void logoutPointcut() {

    }

    // 通知
    @Before("logoutPointcut()")
    private String beforeLogou() throws Throwable {



        MarketLog marketLog = new MarketLog();

        // 获取用户名
        MarketAdmin principal = (MarketAdmin) SecurityUtils.getSubject().getPrincipal();
        marketLog.setAdmin(principal.getUsername());

        // 获取访问ip
        marketLog.setIp(getIp());

        // 获取操作类型（默认操作类型为1：安全操作）
        marketLog.setType(SUCCESSFUL);

        // 获取操作行为
        marketLog.setAction("退出登录");

        // 获取操作结果
        marketLog.setStatus(true);

        // 获取操作时间
        Date date = new Date();
        marketLog.setAddTime(date);
        marketLog.setUpdateTime(date);

        // 增加日志
        logMapper.insertSelective(marketLog);

        // 更新用户表中登录状态
        MarketAdmin marketAdmin = new MarketAdmin();
        marketAdmin.setUpdateTime(date);
        marketAdmin.setId(principal.getId());
        adminMapper.updateByPrimaryKeySelective(marketAdmin);

        return null;
    }



    @Pointcut("@annotation(com.cskaoyan.config.zhangshizhi.CountTime)")
    public void pointcut() {

    }


    // 通知
    @Around("pointcut()")
    private Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取访问ip
        String ip = getIp();

        MarketLog marketLog = new MarketLog();
        marketLog.setIp(ip);
        // 默认操作结果为false
        marketLog.setStatus(false);

        // 默认操作类型为1
        marketLog.setType(SUCCESSFUL);

        // 执行委托类方法
        Object proceed = joinPoint.proceed();

        // TODO：可以增加一个异常处理
        marketLog.setStatus(true);


        // 获取操作时间
        Date date = new Date();
        marketLog.setAddTime(date);
        marketLog.setUpdateTime(date);
        // 获取方法名
        String name = joinPoint.getSignature().getName();
        marketLog.setAction(reasoultMap.get(name));

        // 获取用户名
        MarketAdmin principal = (MarketAdmin) SecurityUtils.getSubject().getPrincipal();
        if(principal != null){
            String username = principal.getUsername();
            marketLog.setAdmin(username);
            System.out.println(ip + ":" + username + "=====" +reasoultMap.get(name));
        }else {
            System.out.println(ip + ":" + "   " + "=====" +reasoultMap.get(name));
        }
        logMapper.insertSelective(marketLog);
        return proceed;
    }
    static Map<String, String> reasoultMap = new HashMap<>();

    static {

        reasoultMap.put("login","登录");
        reasoultMap.put("logout","退出登录");

        reasoultMap.put("goodsList","查询商品");
        reasoultMap.put("goodsCreate","添加商品");
        reasoultMap.put("goodsUpdate","编辑商品");
        reasoultMap.put("goodsDelete","删除商品");
        reasoultMap.put("goodsDetail","查看商品详情");
        reasoultMap.put("catAndBrand","商品上架");

        reasoultMap.put("commentList","查看评论");
        reasoultMap.put("commentDelete","删除评论");

        reasoultMap.put("adList","查询广告");
        reasoultMap.put("adCreate","添加广告");
        reasoultMap.put("adUpdate","编辑广告");
        reasoultMap.put("adDelete","删除广告");

        reasoultMap.put("couponList","查询优惠券");
        reasoultMap.put("couponCreate","添加优惠券");
        reasoultMap.put("couponUpdate","编辑优惠券");
        reasoultMap.put("couponDelete","删除优惠券");
        reasoultMap.put("couponRead","查询优惠券详情");

        reasoultMap.put("topicList","查询专题");
        reasoultMap.put("topicCreate","添加专题");
        reasoultMap.put("topicUpdate","编辑专题");
        reasoultMap.put("topicDelete","删除单个专题");
        reasoultMap.put("topicBatchDelete","批量删除专题");

        reasoultMap.put("adminSelect","查询管理员");
        reasoultMap.put("adminCreate","添加管理员");
        reasoultMap.put("adminUpdate","编辑管理员");
        reasoultMap.put("adminRemove","删除管理员");

        reasoultMap.put("logList","查询操作日志");

        reasoultMap.put("roleSelect","查询角色");
        reasoultMap.put("roleCreate","添加角色");
        reasoultMap.put("roleUpdate","编辑角色");
        reasoultMap.put("roleRemove","删除角色");
        reasoultMap.put("rolePermissionsUpdate","授权角色");

        reasoultMap.put("storageSelect","查询对象");
        reasoultMap.put("storageCreate","添加对象");
        reasoultMap.put("storageUpdate","编辑对象");
        reasoultMap.put("storageDelete","删除对象");

        reasoultMap.put("mall","商场配置");
        reasoultMap.put("changeMall","编辑商场配置");
        reasoultMap.put("express","运费配置");
        reasoultMap.put("changeExpress","编辑运费配置");
        reasoultMap.put("order","订单配置");
        reasoultMap.put("changeOrder","编辑订单配置");
        reasoultMap.put("wx","小程序配置");
        reasoultMap.put("changeWx","编辑小程序配置");

        reasoultMap.put("user","用户统计");
        reasoultMap.put("goods","订单统计");
        reasoultMap.put("order","商品统计");

    }


}
